import json
from tqdm import tqdm

def process_json_tags():
    # 直接在代码中指定JSON文件路径
    source_file = "final_dataset_gongzhuang.json"  # 包含title字段的JSON文件
    target_file = "processed_gongzhuangdata_tag/test/cleaned_test.json"  # 包含tag字段的JSON文件
    output_file = "processed_gongzhuangdata_tag/test/output_nocleaned.json"  # 输出文件
    
    try:
        # 读取源JSON文件
        with open(source_file, 'r', encoding='utf-8') as f:
            source_data = json.load(f)
        
        # 读取目标JSON文件
        with open(target_file, 'r', encoding='utf-8') as f:
            target_data = json.load(f)
        
        # 确保两个文件都是列表格式
        if not isinstance(source_data, list):
            source_data = [source_data]
        if not isinstance(target_data, list):
            target_data = [target_data]
        
        # 创建源数据的映射，键为image，值为对应的项
        source_map = {item.get('image', ''): item for item in source_data}
        
        # 处理目标数据中的每个项
        total_items = len(target_data)
        for i, item in enumerate(tqdm(target_data, desc="处理进度", unit="项")):
            target_image = item.get('image', '')
            
            # 查找对应的源数据项
            if target_image in source_map:
                source_item = source_map[target_image]
                
                # 处理源文件中的title字段
                title = source_item.get('title', '')
                if not title:
                    continue
                
                title_parts = title.split()
                if not title_parts:
                    continue
                
                # 提取第一个元素和剩余元素
                first_part = title_parts[0]
                remaining_parts = title_parts[1:]
                
                # 获取目标文件中的tag字段并分割
                target_tags = item.get('tag', '').split(',')
                
                # 合并标签
                merged_tags = [first_part] + remaining_parts + target_tags
                
                # 去重并保持顺序
                unique_tags = []
                for tag in merged_tags:
                    tag = tag.strip()
                    if tag and tag not in unique_tags:
                        unique_tags.append(tag)
                
                # 更新目标数据
                item['tag'] = ','.join(unique_tags)
        
        # 写入输出文件
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(target_data, f, ensure_ascii=False, indent=2)
        
        print(f"处理完成，结果已保存到: {output_file}")
            
    except Exception as e:
        print(f"处理过程中发生错误: {e}")

if __name__ == "__main__":
    process_json_tags()    